package cn.lhc.test.datasyn.common.validator;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @ProjectName: uublog
 * @Package: cn.lhc.test.datasyn.common.validator
 * @ClassName: ValidatorUtil
 * @Author: lhc
 * @Description: TODO
 * @Date: 2019/9/7 上午 12:10
 */
@Slf4j
public class ValidatorUtil {

    public static Validator initValidator() {
        // 使用HibernateValidator
        Validator validator = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 快速失败（即：第一个参数校验失败就返回错误信息，而不是校验所有的参数，并一次性返回所有的错误信息）
                .failFast(true)
                .buildValidatorFactory()
                .getValidator();
        return validator;
    }

    public static void validateObject(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = initValidator().validate(object, groups);
        if (constraintViolations.size() > 0) {
            for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
                String message = constraintViolation.getMessage();
                throw new ConstraintNotMatchException(message);
            }
        }
    }
}
